/*
 * Copyright (c) 2015 LingoChamp Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.living.filedownloader;

import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadMonitor;
import com.living.filedownloader.event.EventDownloadComplete;

import org.greenrobot.eventbus.EventBus;


/**
 * 全局的文件下载监听
 * Created by wangq
 */
public class GlobalTaskMonitor implements FileDownloadMonitor.IMonitor {
    private final static String TAG = "GlobalMonitor";

    private volatile int markStart;
    private volatile int markOver;
    private volatile int downloading;

    private final static class HolderClass {
        private final static GlobalTaskMonitor INSTANCE = new GlobalTaskMonitor();
    }

    public static GlobalTaskMonitor getImpl() {
        return HolderClass.INSTANCE;
    }


    @Override
    public void onRequestStart(int count, boolean serial, FileDownloadListener lis) {
        markStart = 0;
        markOver = 0;
        Log.d(TAG, String.format("on request start %d %B", count, serial));
    }

    @Override
    public void onRequestStart(BaseDownloadTask task) {
        Log.d(TAG, " onRequestStart ： " + task.getUrl());
    }

    @Override
    public void onTaskBegin(BaseDownloadTask task) {
        markStart++;
    }

    @Override
    public void onTaskStarted(BaseDownloadTask task) {
        Log.d(TAG, " onTaskStarted ： " + task.getUrl());
        downloading++;
    }

    @Override
    public void onTaskOver(BaseDownloadTask task) {
        markOver++;
        downloading--;
        EventBus.getDefault().post(new EventDownloadComplete());
        GlobalTasksManager.getInstance().removeTaskForViewHolder(task.getId());
        Log.d(TAG, " onTaskOver ： " + task.getUrl() + "  getStatus: " + task.getStatus());
    }

    public int getMarkStart() {
        return markStart;
    }

    public int getMarkOver() {
        return markOver;
    }

    public int getDownloading() {
        return downloading;
    }

}
